"use strict";
const common_vendor = require("../../common/vendor.js");
const utils_index = require("../../utils/index.js");
const { getCachedAnalysisResult, cacheAnalysisResult } = utils_index;
const __unplugin_components_1 = () => "../../node-modules/wot-design-uni/components/wd-button/wd-button.js";
const __unplugin_components_0 = () => "../../node-modules/wot-design-uni/components/wd-icon/wd-icon.js";
if (!Array) {
  const _component_wd_icon = __unplugin_components_0;
  const _component_wd_button = __unplugin_components_1;
  const _component_layout_default_uni = common_vendor.resolveComponent("layout-default-uni");
  (_component_wd_icon + _component_wd_button + _component_layout_default_uni)();
}
const _sfc_main = /* @__PURE__ */ common_vendor.defineComponent({
  __name: "index",
  setup(__props) {
    const imageList = common_vendor.ref([]);
    const fileObj = common_vendor.ref(null);
    const imageBase64 = common_vendor.ref("");
    const imageFormat = common_vendor.ref("jpeg");
    
    // 进度条相关状态
    const isLoading = common_vendor.ref(false);
    const progressValue = common_vendor.ref(0);
    const progressText = common_vendor.ref("准备分析中...");
    
    // 更新进度条
    function updateProgress(value, text) {
      progressValue.value = value;
      progressText.value = text;
    }

    function chooseImage() {
      if (typeof window !== "undefined") {
        const input = document.createElement("input");
        input.type = "file";
        input.accept = "image/*";
        input.onchange = (e) => {
          var _a;
          const target = e.target;
          if (target.files && target.files[0]) {
            const file = target.files[0];
            fileObj.value = file;
            const tempUrl = URL.createObjectURL(file);
            imageList.value = [tempUrl];
            const fileName = file.name;
            const extension = (_a = fileName.split(".").pop()) == null ? void 0 : _a.toLowerCase();
            imageFormat.value = extension === "png" ? "png" : extension === "webp" ? "webp" : "jpeg";
            const reader = new FileReader();
            reader.onload = function(e2) {
              if (e2.target && e2.target.result) {
                imageBase64.value = e2.target.result;
                // console.info("H5环境图片Base64前50字符:", imageBase64.value.substring(0, 50));
              }
            };
            reader.readAsDataURL(file);
          }
        };
        input.click();
      } else {
        common_vendor.index.chooseImage({
          count: 1,
          success: (res) => {
            var _a;
            const tempFilePaths = res.tempFilePaths;
            imageList.value = tempFilePaths;
            const filePath = tempFilePaths[0];
            const extension = (_a = filePath.split(".").pop()) == null ? void 0 : _a.toLowerCase();
            imageFormat.value = extension === "png" ? "png" : extension === "webp" ? "webp" : "jpeg";
            common_vendor.index.getFileSystemManager().readFile({
              filePath,
              encoding: "base64",
              success: (result) => {
                imageBase64.value = `data:image/${imageFormat.value};base64,${result.data}`;
                // console.info("小程序环境图片Base64前50字符:", imageBase64.value.substring(0, 50));
              },
              fail: (error) => {
                console.error("图片转base64失败:", error);
              }
            });
          }
        });
      }
    }
    function removeImage() {
      imageList.value = [];
      fileObj.value = null;
    }
    async function analyzeCalorie() {
      if (utils_index.checkUsageLimit()) {
        common_vendor.index.showToast({
          title: "今日使用次数已达上限，请明天再来",
          icon: "none",
          duration: 3e3
        });
        return;
      }
      // console.info("开始分析图片卡路里");
      if (!imageList.value[0]) {
        common_vendor.index.showToast({
          title: "请先上传图片",
          icon: "none"
        });
        return;
      }
      
      // 先检查是否有缓存的分析结果
      const cachedResult = getCachedAnalysisResult(imageBase64.value);
      if (cachedResult) {
        // console.info("使用缓存的分析结果");
        // 直接使用缓存结果，不需要增加使用次数
        setTimeout(() => {
          common_vendor.index.navigateTo({
            url: `/pages/calorie-camera/result?result=${encodeURIComponent(JSON.stringify(cachedResult))}`
          });
        }, 200);
        return;
      }

      // 显示进度条
      isLoading.value = true;
      updateProgress(0, "开始分析...");
      
      // 短暂延迟后更新到10%
      await new Promise(resolve => setTimeout(resolve, 200));
      updateProgress(10, "正在预处理图片...");

      try {
        // console.info("开始食物图片检测");
        updateProgress(20, "正在检测是否为食物图片...");
        
        // 短暂延迟后更新到30%
        await new Promise(resolve => setTimeout(resolve, 200));
        updateProgress(30, "正在提取图片特征...");
        
        const foodDetectionResult = await utils_index.callDoubanApi([
          {
            "role": "system",
            "content": '你是一个专业的图像分析专家，任务是判断图片中是否包含食物。请严格按照以下要求进行分析：\n1. 如果图片中明显包含食物、菜品或饮料等内容，请返回：{"hasFood": true}\n2. 如果图片中不包含食物相关内容，请返回：{"hasFood": false}\n3. 请严格按照JSON格式返回，不要添加额外文字。'
          },
          {
            "role": "user",
            "content": [
              {
                "type": "text",
                "text": "请判断这张图片中是否包含食物"
              },
              {
                "type": "image_url",
                "image_url": {
                  url: imageBase64.value
                }
              }
            ]
          }
        ]);
        
        updateProgress(40, "食物检测完成，开始营养分析...");
        
        // 短暂延迟后更新到50%
        await new Promise(resolve => setTimeout(resolve, 200));
        updateProgress(50, "正在识别食物种类...");
        
        // console.info("食物图片检测结果:", foodDetectionResult);
        const foodDetectionResponse = foodDetectionResult.choices[0].message.content;
        // console.info("食物图片检测AI回答:", foodDetectionResponse);
        let foodDetectionData;
        try {
          foodDetectionData = JSON.parse(foodDetectionResponse);
        } catch (e) {
          console.error("食物图片检测结果解析失败:", e);
          common_vendor.index.showToast({
            title: "食物检测失败，请重试",
            icon: "error"
          });
          isLoading.value = false;
          return;
        }
        if (!foodDetectionData.hasFood) {
          common_vendor.index.showToast({
            title: "请上传有效的食物图片",
            icon: "none",
            duration: 3e3
          });
          isLoading.value = false;
          return;
        }
        
        updateProgress(60, "正在进行营养分析...");
        
        // 短暂延迟后更新到70%
        await new Promise(resolve => setTimeout(resolve, 200));
        updateProgress(70, "正在计算卡路里含量...");
        
        // console.info("食物图片检测通过，开始营养分析");
        const result = await utils_index.callDoubanApi([
          {
            role: "system",
            content: '你是一位专业的营养师和食物分析师，拥有丰富的营养学知识和临床经验。请分析用户提供的食物图片，识别图片中的食物，并提供详细、专业、有说服力的分析报告。请严格按照以下JSON格式返回：\n{\n  "foodName": "详细食物名称",\n  "foodType": "食物类别",\n  "calorie": 卡路里数值,\n  "servingSize": "详细份量描述",\n  "confidence": "识别可信度(%)",\n  "nutrients": [\n    {"name": "蛋白质", "value": "数值", "unit": "克"},\n    {"name": "脂肪", "value": "数值", "unit": "克"},\n    {"name": "碳水化合物", "value": "数值", "unit": "克"},\n    {"name": "膳食纤维", "value": "数值", "unit": "克"},\n    {"name": "糖", "value": "数值", "unit": "克"}\n  ],\n  "macronutrientRatio": {\n    "proteinPercentage": "蛋白质供能占比(%)",\n    "fatPercentage": "脂肪供能占比(%)",\n    "carbsPercentage": "碳水供能占比(%)"\n  },\n  "keyIngredients": ["主要成分1", "主要成分2", "主要成分3"],\n  "nutritionalEvaluation": {\n    "energyDensity": "能量密度评估(低/中/高)",\n    "nutrientBalance": "营养均衡性评估",\n    "healthImpact": "健康影响简要说明"\n  },\n  "dietAdvice": {\n    "summary": "饮食建议总结",\n    "portionControl": "份量控制建议",\n    "mealTiming": "食用时间建议",\n    "suitableFor": "适合人群",\n    "notSuitableFor": "不适合人群",\n    "pairingSuggestions": ["搭配建议1", "搭配建议2"]\n  }\n}\n\n请确保分析内容专业、具体、有科学依据，让用户感到分析可信且有实用价值。不要添加任何额外文字。'
          },
          {
            "role": "user",
            "content": [
              {
                "type": "text",
                "text": "请分析这张食物图片，提供专业的营养分析和实用的饮食建议，确保分析内容具体、有科学依据，让我感到可信且有帮助。"
              },
              {
                "type": "image_url",
                image_url: {
                  url: imageBase64.value
                }
              }
            ]
          }
        ]);
        
        updateProgress(80, "正在分析营养成分...");
        
        // 短暂延迟后更新到90%
        await new Promise(resolve => setTimeout(resolve, 200));
        updateProgress(90, "正在生成健康建议...");
        
        // console.info("result", result);
        // console.info("ai回答", result.choices[0].message.content);
        
        // 缓存分析结果
        cacheAnalysisResult(imageBase64.value, result);
        
        utils_index.increaseUserUsageCount();
        
        updateProgress(100, "分析完成，正在跳转...");
        
        // 延迟跳转，让用户看到完成状态
        setTimeout(() => {
          isLoading.value = false; // 隐藏进度条
          common_vendor.index.navigateTo({
            url: `/pages/calorie-camera/result?result=${encodeURIComponent(JSON.stringify(result))}`
          });
        }, 500);
      } catch (error) {
        console.error("分析失败:", error);
        isLoading.value = false; // 隐藏进度条
        common_vendor.index.showToast({
          title: "分析失败，请重试",
          icon: "error"
        });
      }
    }
    function navigateBack() {
      // 隐藏进度条
      isLoading.value = false;
      // 检查页面栈，避免在首页调用navigateBack报错
      const pages = getCurrentPages();
      if (pages.length > 1) {
        common_vendor.index.navigateBack();
      } else {
        // 如果是第一个页面，跳转到首页
        common_vendor.index.switchTab({
          url: '/pages/index/index'
        });
      }
    }

    return (_ctx, _cache) => {
      return common_vendor.e({
        a: common_vendor.p({
          name: "arrow-left",
          size: "20px"
        }),
        b: common_vendor.o(navigateBack),
        c: common_vendor.p({
          name: "fire",
          size: "16px",
          color: "#FF7D00"
        }),
        d: imageList.value.length === 0
      }, imageList.value.length === 0 ? {
        e: common_vendor.p({
          name: "upload",
          size: "60rpx",
          color: "#ccc"
        })
      } : {
        f: imageList.value[0],
        g: common_vendor.p({
          name: "close",
          size: "24rpx",
          color: "#fff"
        }),
        h: common_vendor.o(($event) => removeImage())
      }, {
        i: common_vendor.o(chooseImage),
        j: common_vendor.o(analyzeCalorie),
        k: common_vendor.p({
          type: "primary"
        }),
        l: isLoading.value,
        m: progressValue.value,
        n: common_vendor.t(progressText.value),
        o: common_vendor.o(navigateBack)
      });
    };
  }
});
const MiniProgramPage = /* @__PURE__ */ common_vendor._export_sfc(_sfc_main, [["__scopeId", "data-v-373a8189"]]);
wx.createPage(MiniProgramPage);
